package com.maltys.redission.raw;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author malty
 */
@Data
@Component
public class RawRedisLockV2 {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 加锁操作
     *
     * @param key      key
     * @param value    value 可以使用uuid，将来用来验证是否是自己加的锁
     * @param expire   过期时间
     * @param timeUnit 时间单位
     * @return 是否成功获取锁
     */
    public boolean tryLock(String key, String value, long expire, TimeUnit timeUnit) {
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit));
    }

    /**
     * 解锁操作
     *
     * @param key   key
     * @param value 可以使用uuid，验证是否是自己加的锁
     */
    public boolean releaseLock(String key, String value) {
        DefaultRedisScript<Long> unlockScript = new DefaultRedisScript();
        unlockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("unlock.lua")));
        unlockScript.setResultType(Long.class);
        Long result = stringRedisTemplate.execute(unlockScript, Arrays.asList(key), value);
        assert result != null;
        return result.intValue() == 1;
    }
}
